package com.hooper.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hooper.hosp.model.hosp.Department;
import com.hooper.hosp.repository.DepartmentRepository;
import com.hooper.hosp.service.DepartmentService;
import com.hooper.hosp.utils.MongoPageUtils;
import com.hooper.hosp.vo.DepartmentVo;
import com.hooper.hosp.vo.hosp.DepartmentQueryVo;
import com.hooper.hospital.common.exception.HospitalException;
import com.hooper.hospital.common.result.ResultCodeEnum;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hooper.hospital.common.constant.HospConstant.*;
import static com.hooper.hospital.common.result.ResultCodeEnum.NO_SUCH_DATA;
import static com.hooper.hospital.common.result.ResultCodeEnum.PARAM_EMPTY;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2022/09/28/15:07
 */
@Service
@RequiredArgsConstructor
public class DepartmentServiceImpl implements DepartmentService {

    private final DepartmentRepository departmentRepository;

    @Override
    public boolean saveOrUpdate(Map<String, Object> map) {

        Department department = null;
        try {
            //convert the map to Json then convert Json to Department Obj
            department = JSONObject.parseObject(JSONObject.toJSONString(map), Department.class);
        } catch (Exception exception) {
            throw new RuntimeException("Cannot convert the data to Department!");
        }

        //retrieve the db, find if the data has already existed
        Department dbDepartment = departmentRepository.findDepartmentByDepcodeAndHoscode(department.getDepcode(), department.getHoscode());
        if (dbDepartment == null) {
            //if this is a new one set the following default attributes
            department.setCreateTime(TIME_NOW);
            department.setIsDeleted(NOT_DELETED);
        } else {
            //else give the existed id to the new data
            department.setId(dbDepartment.getId());
        }
        department.setUpdateTime(TIME_NOW);
        //save or update
        departmentRepository.save(department);
        return true;
    }

    @Override
    public Page<Department> pageDepartment(int page, int limit, DepartmentQueryVo departmentVo) {

        //set page size and current page
        Pageable pageAble = MongoPageUtils.getPageable(page, limit);

        //the Example obj need Department obj, use BeanUtils to copy
        Department department = new Department();
        BeanUtils.copyProperties(departmentVo, department);
        department.setIsDeleted(NOT_DELETED);
        //config fuzzy query
        Example<Department> example = MongoPageUtils.getExample(department);

        //query
        return departmentRepository.findAll(example, pageAble);
    }

    @Override
    public void removeByHoscode(String hoscode, String depcode) {
        if (StringUtils.isAnyBlank(hoscode, depcode)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        Department department = departmentRepository.findDepartmentByDepcodeAndHoscode(depcode, hoscode);
        department.setIsDeleted(IS_DELETED);
    }

    @Override
    public List<DepartmentVo> getDepartmentListByHoscode(String hoscode) {
        if (StringUtils.isEmpty(hoscode)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        List<Department> departmentList = departmentRepository.findAllByHoscode(hoscode);
        if (departmentList == null || departmentList.size() == 0){
            throw new HospitalException(NO_SUCH_DATA);
        }
        //group by the superior hospital department code which is the 'big code'
        // which means the result would be like (key-> big code) =>(value -> all the departments whose big codes are equal)
        Map<String, List<Department>> departmentMap = departmentList.stream().collect(Collectors.groupingBy(Department::getBigcode));

        List<DepartmentVo> departmentVoList = new ArrayList<>();
        //traverse the map
        for (Map.Entry<String, List<Department>> entry : departmentMap.entrySet()) {
            //the key is the superior code
            String key = entry.getKey();
            //the value is the departments whose big code equals the key
            List<Department> value = entry.getValue();

            //new vo set the superior hospital department code as the depcode
            DepartmentVo departmentVo = new DepartmentVo();
            departmentVo.setDepcode(key);
            //check if the value is empty
            if (value != null && value.size() != 0) {
                //set the superior hospital department name
                departmentVo.setDepname(value.get(0).getBigname());
                //reflect the department to the inferior department view object
                List<DepartmentVo> children = value.stream().map(item -> {
                    DepartmentVo tempt = new DepartmentVo();
                    tempt.setDepname(item.getDepname());
                    tempt.setDepcode(item.getDepcode());
                    return tempt;
                }).collect(Collectors.toList());
                departmentVo.setChildren(children);
            }
            //add the result to the list
            departmentVoList.add(departmentVo);
        }
        return departmentVoList;
    }

    @Override
    public Department getByDepcode(String depcode) {
        if (StringUtils.isEmpty(depcode)) {
            throw new HospitalException(PARAM_EMPTY);
        }
        return departmentRepository.findByDepcode(depcode);
    }
}
